package com.jingdong.filter;


import org.apache.commons.lang3.StringUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request= (HttpServletRequest) servletRequest;
        HttpServletResponse response= (HttpServletResponse) servletResponse;
        String servletPath=request.getServletPath();
        HttpSession session=request.getSession();
        String sessionKey = (String) session.getAttribute(Constant.SESSIONKEY);
        if ( servletPath.endsWith(".js") || servletPath.endsWith(".css") || servletPath.endsWith(".jpg")||servletPath.endsWith(".jpeg")) {
            filterChain.doFilter(servletRequest, servletResponse);//放行
        }
        if ( servletPath.contains("/user/toLogin")||servletPath.contains("/user/captcha")||servletPath.contains("/user/login")) {
            filterChain.doFilter(servletRequest, servletResponse);//放行
        }else if (!StringUtils.isEmpty(sessionKey) ) {
            filterChain.doFilter(servletRequest, servletResponse);//放行
        } else {
            response.sendRedirect(request.getContextPath() + "/user/toLogin");//过滤
        }
    }

    @Override
    public void destroy() {

    }
}
